import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Popconfirm } from 'antd';
import { history } from 'umi';
import React, { useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { remove, update } from './service';
import { hospitalDeptlist } from '@/services/ant-design-pro/api';
import type { TableListItem, TableListPagination } from './data';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const handleShow = async (record: API.RuleListItem[]) => {
    const hide = message.loading('正在处理');
    let item = { id: record.id };
    item.status = record.status == 0 ? 1 : 0;
    try {
      const response = await update(item);
      if (response.code == 200) {
        message.success('处理成功,即将刷新');
      } else {
        message.error('处理失败!');
      }
      hide();
      actionRef.current ?.reloadAndRest ?.();
    } catch (error) {
      hide();
      message.error('处理失败');
      return false;
    }
  };

  /** 国际化配置 */

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '科室名称',
      dataIndex: 'name',
      width: '150px',
    },
    {
      title: '科室等级',
      dataIndex: 'level',
      hideInForm: true,
      hideInSearch: true,
      width: '150px',
      render: (text, _, index) => {
        return text == 1 ? '一级' : '二级';
      },
    },
    {
      title: '上级科室',
      dataIndex: 'parentName',
      hideInForm: true,
      hideInSearch: true,
      width: '150px',
    },
    {
      title: '同级排序',
      dataIndex: 'sort',
      hideInForm: true,
      hideInSearch: true,
      width: '150px',
    },
    {
      title: '是否科普明星科室',
      dataIndex: 'isMain',
      hideInForm: true,
      hideInSearch: true,
      width: '150px',
      render: (text, _, index) => {
        return text == 1 ? '是' : '否';
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: '180px',
      render: (_, record) => [
        <a
          key="eidt"
          onClick={() => {
            history.push('/hospital/dept-detail?id=' + record.id);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="top"
          title={record.status == 0 ? '确定要隐藏吗?' : '确定要显示吗?'}
          onConfirm={() => handleShow(record)}
        >
          <a>{record.status == 0 ? '隐藏' : '显示'}</a>
        </Popconfirm>,
      ],
    },
  ];

  /**
   * 删除节点
   *
   * @param selectedRows
   */

  const handleRemove = async (id: Number) => {
    const hide = message.loading('正在删除');
    try {
      await remove({
        key: id,
      });
      hide();
      message.success('删除成功，即将刷新');
      actionRef.current ?.reloadAndRest ?.();
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  return (
    <PageContainer>
      <ProTable<TableListItem, TableListPagination>
        actionRef={actionRef}
      rowKey="id"
        search={{
        labelWidth: 120,
      }}
      headerTitle={
        sessionStorage.getItem(`hosiptaAuthlId`) != 0 ? (
          <div>
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                history.push('/hospital/dept-detail');
              }}
            >
              <PlusOutlined /> 新增
              </Button>
            <span style={{ color: '#33333390', paddingLeft: '10px', fontSize: '14px' }}>
              如果您操作遇到困难，请联系医中心运营帮助修改科室信息
              </span>
          </div>
        ) : null
      }
      request={async (
        // 第一个参数 params 查询表单和 params 参数的结合
        // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
        params,
        sorter,
        filter,
      ) => {
        // console.log(params, sorter, filter);
        // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
        // 如果需要转化参数可以在这里进行修改
        let likeQuery = {};
        if (params.name != '') {
          likeQuery.name = params.name;
        }
        if (params.hospitalName != '') {
          likeQuery.hospital_name = params.hospitalName;
        }
        let query = {
          asc: true,
          sortFiled: 'hospital_id',
          pageNum: params.current,
          pageSize: params.pageSize,
        };
        console.log(
          'sessionStorage.getItem(`hosiptalId`)',
          sessionStorage.getItem(`hosiptaAuthlId`),
        );
        if (sessionStorage.getItem(`hosiptaAuthlId`)) {
          let eqQuery = {};
          eqQuery.hospitalId = sessionStorage.getItem(`hosiptaAuthlId`);
          query.eqQuery = eqQuery;
        }
        query.likeQuery = likeQuery;
        const msg = await hospitalDeptlist(query);
        console.log('msg', msg);
        if (msg.code == 200) {
          return {
            data: msg.data.list,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: msg.message,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: msg.data.total,
          };
        } else {
        }
      }}
      columns={columns}
      />
    </PageContainer>
  );
};

export default TableList;
